package com.ecole.mines.emargement;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Fragment;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.ecole.mines.model.Cours;
import com.ecole.mines.model.Eleve;
import com.ecole.mines.model.Promotion;
import com.ecole.mines.model.Signature;

public class FragmentCadreSignature extends Fragment {

	Eleve eleveSelectionne;
	Button annuler;
	Button valider;
	View view;
	SignatureView signatureView;
	private String dirCurrentDate;
	private String dirPromo = "Promo";
	private File fileDir;
	private Promotion promotion;
	public static final String EXTERNAL_DIR = "Emargement";

	public Eleve getEleveSelectionne() {
		return eleveSelectionne;
	}

	public void setEleveSelectionne(Eleve eleveSelectionne) {
		this.eleveSelectionne = eleveSelectionne;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// Promotion
		promotion = ((EmargementActivity) getActivity()).getPromotion();
		dirPromo = promotion.getName().trim().replace(" ", "");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.activity_fragment_cadre_signature,
				container, false);

		// Initialisation des boutons
		annuler = (Button) view.findViewById(R.id.buttonAnnuler);
		annuler.setOnClickListener(listenerBtn);
		valider = (Button) view.findViewById(R.id.buttonValider);
		valider.setOnClickListener(listenerBtn);

		signatureView = (SignatureView) view.findViewById(R.id.drawing);
		// Si un élève a été sélectionné, les boutons sont activés, sinon non
		if (signatureView.eleveSelectionne != null && !signatureView.eleveSelectionne.getHasSigned()) {
			FragmentListeEleves.activerBoutons(valider, annuler);
			valider.setEnabled(true);
			annuler.setEnabled(true);
			signatureView.setEnabled(true);
		} else {
			FragmentListeEleves.desactiverBoutons(valider, annuler);
			valider.setEnabled(false);
			annuler.setEnabled(false);
			signatureView.setEnabled(false);
		}
		return view;
	}

	View.OnClickListener listenerBtn = new View.OnClickListener() {
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.buttonAnnuler:
				effacerSignature();
				break;
			case R.id.buttonValider:
				enregistrerSignature();
				break;
			}
		}

	};

	public void enregistrerSignature() {
		if (signatureView.getZoneSignatureVide()) {
			return;
		}
		signatureView.setSignatureActive(false);

		eleveSelectionne = signatureView.eleveSelectionne;
		ArrayList<Signature> signatures = eleveSelectionne.getSignatures();
		Bitmap bitmapImage = Bitmap.createBitmap(signatureView
				.enregistrerSignature());

		if (dirCurrentDate == "" || dirCurrentDate == null) {
			dirCurrentDate = getTodaysDate() + "_" + getCurrentTime();
		}

		String current = eleveSelectionne.getId() + "_"
				+ eleveSelectionne.getSignatures().size() + ".png";
		createDirectoryAndSaveFile(bitmapImage, current);

		// Préparation de la signature
		Signature signature = new Signature();
		signature.setHeureSignature(getCurrentTimeLong());
		signature.setImageSignature(bitmapImage);
		signature.setDirectory(fileDir.getParentFile());
		signature.setNamefile(current);
		// TODO déterminer si retard ou non
		signature.setRetard(false);
		signatures.add(signature);
		// signatureView.effacerZoneSignature();
		eleveSelectionne.setHasSigned(true);
		eleveSelectionne.setSignatures(signatures);

		((EmargementActivity) getActivity())
				.enregistrerEleveJson(eleveSelectionne);
	}

	public void enregistrerSignature(Eleve eleveSelectionne, Bitmap bitmapImage) {
		signatureView.setSignatureActive(true);
		ArrayList<Signature> signatures = eleveSelectionne.getSignatures();
		if (dirCurrentDate == "" || dirCurrentDate == null) {
			dirCurrentDate = getTodaysDate() + "_" + getCurrentTime();
		}

		String current = eleveSelectionne.getId() + "_"
				+ eleveSelectionne.getSignatures().size() + ".png";
		createDirectoryAndSaveFile(bitmapImage, current);

		System.out.println("Enregistrement signature");
		// Préparation de la signature
		Signature signature = new Signature();
		signature.setHeureSignature(getCurrentTimeLong());
		signature.setImageSignature(bitmapImage);
		signature.setDirectory(fileDir.getParentFile());
		signature.setNamefile(current);
		// TODO déterminer si retard ou non
		signature.setRetard(false);
		signatures.add(signature);
		// signatureView.effacerZoneSignature();
		eleveSelectionne.setHasSigned(true);
		eleveSelectionne.setSignatures(signatures);

		((EmargementActivity) getActivity())
				.enregistrerEleveJson(eleveSelectionne);

		Toast.makeText(getActivity(), "Signature enregistrée",
				Toast.LENGTH_SHORT).show();
	}

	protected void effacerSignature() {
		signatureView.effacerZoneSignature();

	}

	private String getCurrentTime() {

		final Calendar c = Calendar.getInstance();
		int currentTime = (c.get(Calendar.HOUR_OF_DAY) * 10000)
				+ (c.get(Calendar.MINUTE) * 100) + (c.get(Calendar.SECOND));
		return (String.valueOf(currentTime));

	}

	private long getCurrentTimeLong() {

		final Calendar c = Calendar.getInstance();
		long currentTime = (c.get(Calendar.HOUR_OF_DAY) * 10000)
				+ (c.get(Calendar.MINUTE) * 100) + (c.get(Calendar.SECOND));
		return currentTime;

	}

	private String getTodaysDate() {

		final Calendar c = Calendar.getInstance();
		int todaysDate = (c.get(Calendar.YEAR) * 10000)
				+ ((c.get(Calendar.MONTH) + 1) * 100)
				+ (c.get(Calendar.DAY_OF_MONTH));
		return (String.valueOf(todaysDate));

	}

	private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {

		Cours cours = promotion.getCours().get(0);
		String dirGroupeCours = cours.getGroupe().trim() + "_" + cours.getId();

		File directory = new File(Environment.getExternalStorageDirectory()
				.getPath()
				+ File.separator
				+ EXTERNAL_DIR
				+ File.separator
				+ dirPromo
				+ File.separator + dirGroupeCours + File.separator);
		directory.mkdirs();
		fileDir = new File(new File(Environment.getExternalStorageDirectory()
				.getPath()
				+ File.separator
				+ EXTERNAL_DIR
				+ File.separator
				+ dirPromo + File.separator + dirGroupeCours + File.separator),
				fileName);
		if (fileDir.exists()) {
			fileDir.delete();
		}

		try {
			FileOutputStream out = new FileOutputStream(fileDir);
			imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(getActivity(),
					"Impossible d'enregistrer la signature", Toast.LENGTH_SHORT)
					.show();
		}
	}
}
